package org.redmagic.location.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Set;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
import org.redmagic.Request;
import org.redmagic.exception.RedMagicException;

public class JsonRedMagicRequest implements Request {

	private static final transient String MEDIA_TYPE = "application/json";
	
	private final List<List<String>> hierarchy;
	private final Set<String> placeholders;
	
	@JsonCreator
	public JsonRedMagicRequest(@JsonProperty("hierarchy") List<List<String>> hierarchy, 
			                   @JsonProperty("placeholders") Set<String> placeholders) {
		this.hierarchy = hierarchy;
		this.placeholders = placeholders;
	}
	
	@Override
	public List<List<String>> getHierarchy() {
		return hierarchy;
	}
	
	@Override
	public Set<String> getPlaceholders() {
		return placeholders;
	}
	
	@Override
	public String getMediaType() {
		return MEDIA_TYPE;
	}

	@Override
	public String marshall() {
		try {
			return tryMarshall();
		} catch (Exception e) {
			throw new RedMagicException(e.getMessage(), e);
		}
	}
	
	private String tryMarshall() throws JsonGenerationException, IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		JsonFactory f = new JsonFactory();
		JsonGenerator g = f.createJsonGenerator(baos);

		g.writeStartObject();
		writeHierarchyToJsonGenerator(g);
		writePlaceholdersToJsonGenerator(g);
		g.writeEndObject();
		g.close();
		
		return baos.toString();
	}
	
	private void writeHierarchyToJsonGenerator(JsonGenerator generator) throws JsonGenerationException, IOException {
		generator.writeArrayFieldStart("hierarchy");
		for (List<String> tags : hierarchy) {
			generator.writeStartArray();
			for (String tag : tags) {
				generator.writeString(tag);
			}
			generator.writeEndArray();
		}
		generator.writeEndArray();
	}
	
	private void writePlaceholdersToJsonGenerator(JsonGenerator generator) throws JsonGenerationException, IOException {
		generator.writeArrayFieldStart("placeholders");
		for (String placeholder : placeholders) {
			generator.writeString(placeholder);
		}
		generator.writeEndArray();
	}
}
